﻿// Ignore Spelling: Utils

using System;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;

namespace EmbeddedCourseLib
{
    public static class FontUtils
    {
        public static Font GetFontObjectFromName(string fontName)
        {
            return new Font(fontName, 13, FontStyle.Regular, GraphicsUnit.Pixel);
        }

        public static Font GetFontObjectFromTtf(string ttfPath, int index)
        {
            var fontCollection = new PrivateFontCollection();

            // 添加TTF字体文件到PrivateFontCollection中
            fontCollection.AddFontFile(ttfPath);

            // 获取PrivateFontCollection中的字体列表
            var fontFamilies = fontCollection.Families;

            if (index >= fontFamilies.Length)
            {
                throw new Exception("index out of range");
            }

            return new Font(fontFamilies[index], 13f, FontStyle.Regular, GraphicsUnit.Pixel);
        }

        private static string GetChineseCharacterFont(string value, Font font)
        {
            var cArray = "";

            // 创建一个Bitmap对象，并绘制汉字
            var bitmap = new Bitmap(16, 16);
            var graphics = Graphics.FromImage(bitmap);

            // 使用Font对象进行绘制或其他操作
            Console.WriteLine("Font Name: " + font.Name);
            //cArray+= $"\t/* {value} */\n";
            cArray += $"\t/* Font Name: {font.Name} */\n\t";

            graphics.Clear(Color.White);
            graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixelGridFit;
            graphics.DrawString(value, font, Brushes.Black, new PointF(-1, 0));
            // bitmap.Save($"{value}.bmp");

            // 将Bitmap对象转换为二维的0和1的数组
            var binaryArray = new int[16, 16];
            for (var y = 0; y < 16; y++)
            {
                for (var x = 0; x < 16; x++)
                {
                    var pixelColor = bitmap.GetPixel(x, y);
                    binaryArray[y, x] = pixelColor.R == 0 ? 1 : 0;
                }
            }

            // 将二维数组保存为C语言数组

            //cArray += "{";
            for (var y = 0; y < 16; y++)
            {
                var current = 0;
                for (var x = 0; x < 8; x++)
                {
                    current |= binaryArray[y, x] << (8 - x);
                }

                cArray += $"0x{current:X2}, ";

                current = 0;
                for (var x = 8; x < 15; x++)
                {
                    current |= binaryArray[y, x] << (15 - x);
                }

                cArray += $"0x{current:X2}";
                if (y < 15)
                    cArray += ", ";
            }
            //cArray += "}";

            return cArray;
        }

        public static string GetChineseCharacterFontFromString(string str, Font font, string varName)
        {
            str = str.Trim();

            if (string.IsNullOrEmpty(varName))
            {
                throw new Exception("varName is null");
            }

            if (string.IsNullOrEmpty(str))
            {
                throw new Exception("str is null");
            }

            if (font == null)
            {
                throw new Exception("font is null");
            }

            var headerUniqueIdentification = "FONT_" + varName.ToUpper();

            // Remove Repeat
            var charArray = str.ToCharArray().Distinct().ToArray();

            // Remove Space
            charArray = charArray.Where(c => c != ' ').ToArray();

            var cArray = "";
            cArray += "/* This is a Text Pixel Raw Data C Header File. */\n";
            cArray += "/* This file was generated by a tool created by Haomin Kong. */\n\n";

            cArray += $"/* Original: {str} */\t/* Length:{str.Length} */\n";
            var validStr = new string(charArray);
            cArray += $"/* Valid: {validStr} */\t/* Length:{validStr.Length} */\n\n";

            const string sizeOfChar = "16 * 2";

            var spaceCount = 0;
            for (var i = 0; i < str.Length; ++i)
            {
                var currentChar = str[i];
                if (currentChar == ' ')
                {
                    spaceCount++;
                    continue;
                }

                // Find currentChar in validStr
                var index = validStr.IndexOf(currentChar);

                if (index != -1)
                {
                    cArray +=
                        $"/* {currentChar} :\n" +
                        $"\t\t({varName} + {sizeOfChar} * {index})\n" +
                        $"\t\t(start_x + TEXT_WIDTH_HEIGHT * ({i} + {spaceCount}))\n" +
                        $"*/\n";
                }
            }

            cArray += "\n";
            cArray += $"#ifndef {headerUniqueIdentification}\n";
            cArray += $"#define {headerUniqueIdentification}\n\n";

            cArray += "#ifndef SIZE_OF_PER_TEXT\n";
            cArray += $"#define SIZE_OF_PER_TEXT {sizeOfChar}\n";
            cArray += "#endif //SIZE_OF_PER_TEXT\n\n";

            cArray += "#ifndef TEXT_WIDTH_HEIGHT\n";
            cArray += "#define TEXT_WIDTH_HEIGHT 16\n";
            cArray += "#endif //TEXT_WIDTH_HEIGHT\n";

            cArray += "\n";

            cArray += "// Int08U <=> unsigned char (8bit)\n";

            cArray += "\n";

            cArray += $"const unsigned char {varName}[{charArray.Length} * {sizeOfChar}] = \n";
            cArray += "{\n";
            for (var i = 0; i < charArray.Length; i++)
            {
                //cArray += "\t";
                cArray += $"\t/* {i} {charArray[i]} */";
                cArray += GetChineseCharacterFont(charArray[i].ToString(), font);
                if (i < str.Length - 1)
                {
                    cArray += ",";
                }

                cArray += "\n";
            }

            cArray += "};\n";

            cArray += $"\n#endif //{headerUniqueIdentification}\n";

            return cArray;
        }
    }
}